package com.chenfan.ccp.plug.log.util;

import com.chenfan.ccp.utils.TraceIdUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;

public class TraceIdTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        // 获取当前线程调用MDC上下文
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (contextMap != null) {
                    // 设置当前线程上下文map
                    MDC.setContextMap(contextMap);
                }
                String traceId = MDC.get(TraceIdUtil.SHORT_TRACE_ID);
                if (StringUtils.isBlank(traceId)) {
                    MDC.put(TraceIdUtil.SHORT_TRACE_ID, TraceIdUtil.getUUID());
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
